/**
 * StringToLocalTimeConverter.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年1月18日
 */
package com.pshare.util.time;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 字符串转LocalTime转换器
 * 
 */
public class StringToLocalTimeConverter implements Converter<String, LocalTime> {

	@Override
	public LocalTime convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}

		source = source.trim();
		if (!org.springframework.util.StringUtils.hasText(source)) {
			return null;
		}

		int hour = 0, minute = 0, second = 0;
		if (source.length() == 2) {
			hour = Integer.parseInt(source);
		} else if (source.length() == 5 && source.indexOf(":") == 2) {
			String[] ss = source.split("\\:");
			hour = Integer.parseInt(ss[0]);
			minute = Integer.parseInt(ss[1]);
		} else if (source.length() == 8 && source.indexOf(":") == 2 && source.lastIndexOf(":") == 5) {
			String[] ss = source.split("\\:");
			hour = Integer.parseInt(ss[0]);
			minute = Integer.parseInt(ss[1]);
			second = Integer.parseInt(source.substring(6));
		}
		if (hour == 0) {
			throw new IllegalArgumentException("failed to parse LocalTime " + source);
		}

		LocalTime time = LocalTime.of(hour, minute, second);
		return time;
	}

	public static final DateFormat DF_HOUR = new SimpleDateFormat("HH");
	public static final DateFormat DF_MIN = new SimpleDateFormat("HH:mm");
	public static final DateFormat DF_LONG = new SimpleDateFormat("HH:mm:ss");

}
